<!DOCTYPE html PUBLIC>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>后台管理中心</title>
    <link rel="stylesheet" href="/admin/css/pintuer.css"/>
    <link rel="stylesheet" href="/admin/css/admin.css"/>
    <link href="/admin/css/bootstrap.min.css" rel="stylesheet" type="text/css" media="all"/>
    <script src="/admin/js/jquery.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="/admin/js/bootstrap.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="/admin/js/pintuer.js"></script>
    <title>榜单设置</title>
    <style type="text/css">
        .occupation-box {
            border: 1px solid #ddd;
            width: 300px !important;
            height: 100px;
            padding: 20px;
        }
        .occupation-box > label {
            margin-right: 22px;
        }
        .body-content label {
            font-size: 1.5rem;
        }
    </style>
</head>
<body>
<div class="panel admin-panel">
    <div class="panel-head"><strong><span class="icon-pencil-square-o"></span> 榜单信息</strong></div>
    <div id="app" class="body-content">
        <!-- 查询并选中影片的模态框 Modal -->
        <div class="modal modal-lg fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header">
                        <h1 class="modal-title fs-5" id="exampleModalLabel">选择影片</h1>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <ul class="search">
                            <li>
                                <input class="input" type="text" placeholder="输入影片名称" v-model="keyword" @keyup.enter="searchFilm">
                            </li>
                            <li>
                                <button class="button border-blue" @click="searchFilm">搜索</button>
                            </li>
                        </ul>
                        <table class="table table-striped table-hover">
                            <thead>
                            <th>电影名称</th>
                            <th>电影封面</th>
                            <th>操作</th>
                            </thead>
                            <tbody>
                            <!-- 无影片时显示提示 -->
                            <tr v-if="filmList.length === 0">
                                <td colspan="3" align="center">暂无匹配影片</td>
                            </tr>
                            <!-- 有影片时渲染 -->
                            <tr v-for="film in filmList" :key="film.id"> <!-- 必须加:key，避免Vue警告 -->
                                <td>{{film.name}}</td>
                                <td>
                                    <img :src="film.cover" height="100" alt="封面" v-if="film.cover"> <!-- 封面为空时不渲染 -->
                                    <span v-else>无封面</span>
                                </td>
                                <td>
                                    <button class="btn btn-success btn-sm" @click="selectFilm(film)">选中</button>
                                </td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    </div>
                </div>
            </div>
        </div>
        <!-- // Modal-->
        <form method="post" class="form-x" id="form" @submit.prevent="submit">
            <div class="form-group">
                <div class="label">
                    <label>名称：</label>
                </div>
                <div class="field">
                    <input type="hidden" name="id" v-model="ranking.id" />
                    <!-- 只有年份和类别都存在时才显示标题 -->
                    <h1 v-if="ranking.year && ranking.categoryName">
                        {{ranking.year}} 年度最佳 {{ranking.categoryName}} 片
                    </h1>
                    <div class="tips"></div>
                </div>
            </div>
            <div class="form-group">
                <div class="label">
                    <label>年份：</label>
                </div>
                <div class="field">
                    <input type="number" class="input" name="year" v-model="ranking.year" size="100" placeholder="请输入4位年份（如2024）" />
                    <div class="tips"></div>
                </div>
            </div>
            <div class="form-group">
                <div class="label">
                    <label>类别：</label>
                </div>
                <div class="field">
                    <!-- 类别列表加载完成前显示"加载中" -->
                    <select class="input" name="categoryName" v-model="cid" @change="changeCategory" v-if="categoryList.length > 0">
                        <option value="">请选择类别</option> <!-- 添加默认选项 -->
                        <option v-for="category in categoryList" :key="category.id" :value="category.id">
                            {{category.name}}
                        </option>
                    </select>
                    <span v-else>加载中...</span>
                    <div class="tips"></div>
                </div>
            </div>
            <div class="form-group">
                <div class="label">
                    <label>选择影片：</label>
                </div>
                <div class="field">
                    <span v-for="(film,i) in selectedFilmList" :key="film.id" class="badge bg-green" title="双击移除该影片" style ="margin:2px 2px; cursor: pointer;" @dblclick="removeFilm(i)">
                        {{film.name}}
                    </span>
                    <button type="button" class="btn btn-info" data-bs-toggle="modal" data-bs-target="#exampleModal" :disabled="!cid">添加</button> <!-- 未选类别时禁用添加 -->
                    <div class="tips"></div>
                </div>
            </div>
            <div class="form-group">
                <div class="label">
                    <label></label>
                </div>
                <div class="field">
                    <button class="button border-main icon-check-square-o" type="submit"> 提交</button>
                    <button class="button border-red icon-tags" type="button" onclick="window.history.go(-1);"> 返回</button>
                </div>
            </div>
        </form>
    </div>

    <script type="text/javascript" src="/public/js/vue.js"></script>
    <script type="text/javascript" src="/public/js/axios.js"></script>
    <script type="text/javascript" src="/public/js/axios-config.js"></script>

    <script>
        new Vue({
            el: '#app',
            data: {
                cid: null,
                // 初始化ranking的所有字段，确保响应式
                ranking: {
                    id: null,       // 榜单ID（修改时必传）
                    year: null,     // 年份
                    categoryName: '',// 类别名称
                    filmIdList: ''  // 影片ID列表（逗号分隔）
                },
                categoryList: [],
                keyword: '',
                filmList: [],
                selectedFilmList: [],
                submitUrl: "/api/v1/rankingList/save"
            },
            methods: {
                loadFilmDetails(filmIds) {
                    if (filmIds.length === 0) return;
                    // 假设后端提供根据IDs批量查询影片的接口
                    axios.post('/api/v1/film/batch', { ids: filmIds })
                        .then(res => {
                            this.selectedFilmList = res.data || [];
                        })
                        .catch(err => {
                            console.error("加载影片详情失败：", err);
                            alert("加载已选影片失败，请重新选择！");
                        });
                },
                // 切换类别时，设置榜单的categoryName
                changeCategory() {
                    const selectedCategory = this.categoryList.find(item => item.id === this.cid);
                    this.ranking.categoryName = selectedCategory ? selectedCategory.name : '';
                },
                // 提交表单（添加/修改）
                submit() {
                    // 1. 基础校验
                    if (!this.ranking.year || this.ranking.year.toString().length !== 4) {
                        alert("请输入有效的4位年份（如2024）！");
                        return;
                    }
                    if (!this.cid) {
                        alert("请选择电影类别！");
                        return;
                    }
                    if (this.selectedFilmList.length === 0) {
                        alert("请至少选择1部影片！");
                        return;
                    }

                    // 2. 处理影片ID列表（转为逗号分隔的字符串）
                    this.ranking.filmIdList = this.selectedFilmList.map(film => film.id).join(",");

                    // 3. 提交请求
                    axios.post(this.submitUrl, this.ranking)
                        .then(res => {
                            alert(res.message);
                            // 提交成功后返回列表页
                            window.history.go(-1);
                        })
                        .catch(err => {
                            console.error("提交失败：", err);
                            alert("提交失败，请重试！");
                        });
                },
                // 双击移除已选中的影片
                removeFilm(index) {
                    this.selectedFilmList.splice(index, 1);
                },
                // 选中影片并添加到列表
                selectFilm(film) {
                    // 避免重复添加同一部影片
                    const isDuplicate = this.selectedFilmList.some(item => item.id === film.id);
                    if (isDuplicate) {
                        alert(`《${film.name}》已添加，请勿重复选择！`);
                        return;
                    }
                    if (confirm(`确定要选中《${film.name}》吗？`)) {
                        this.selectedFilmList.push(film);
                        // 可选：添加后关闭模态框
                        // document.querySelector('[data-bs-dismiss="modal"]').click();
                    }
                },
                // 搜索影片
                searchFilm() {
                    const params = {
                        pageNum: 1,
                        pageSize: 10,
                        name: this.keyword.trim(), // 去除空格
                        cid: this.cid // 按选中的类别筛选
                    };
                    // 修复：补全URL开头的"/"
                    const url = '/api/v1/film/page';
                    axios.post(url, params)
                        .then(res => {
                            this.filmList = res.data.list || []; // 避免null
                        })
                        .catch(err => {
                            console.error("搜索影片失败：", err);
                            this.filmList = [];
                        });
                },
                // 加载电影类别列表（抽成单独方法，方便复用）
                loadCategoryList() {
                    // 假设后端提供获取类别列表的接口
                    const url = '/api/v1/category/list';
                    return axios.get(url) // 返回Promise，方便异步控制
                        .then(res => {
                            this.categoryList = res.data || [];
                        })
                        .catch(err => {
                            console.error("加载类别列表失败：", err);
                            this.categoryList = [];
                        });
                }
            },
            mounted() {
                this.loadCategoryList().then(() => {
                    const urlObj = new URL(window.location.href);
                    const params = new URLSearchParams(urlObj.search);
                    const rankingId = params.get('id');

                    if (rankingId) {
                        const detailUrl = `/api/v1/rankingList/detail/${rankingId}`;
                        axios.get(detailUrl)
                            .then(res => {
                                // 1. 确保后端返回格式正确（假设res.data是榜单对象）
                                const rankingDetail = res.data || {};

                                // 2. 赋值到ranking，强制转换year为数字（解决number输入框绑定问题）
                                this.ranking.id = rankingDetail.id || null;
                                this.ranking.year = rankingDetail.year ? Number(rankingDetail.year) : null; // 关键修复
                                this.ranking.categoryName = rankingDetail.categoryName || '';

                                // 3. 初始化已选中影片列表（根据后端返回的filmList或filmIdList处理）
                                if (rankingDetail.filmList && rankingDetail.filmList.length > 0) {
                                    // 若后端返回完整影片对象列表，直接赋值
                                    this.selectedFilmList = [...rankingDetail.filmList];
                                } else if (rankingDetail.filmIdList) {
                                    // 若后端只返回filmIdList（逗号分隔字符串），需调用接口查询影片详情
                                    const filmIds = rankingDetail.filmIdList.split(',').filter(id => id);
                                    this.loadFilmDetails(filmIds); // 新增方法：根据ID查影片详情
                                }

                                // 4. 匹配类别ID（cid）
                                const matchedCategory = this.categoryList.find(
                                    item => item.name === this.ranking.categoryName
                                );
                                this.cid = matchedCategory ? matchedCategory.id : null;
                            })
                            .catch(err => {
                                console.error("加载榜单详情失败：", err);
                                alert("加载榜单信息失败，请刷新重试！");
                            });
                        this.submitUrl = "/api/v1/rankingList/update";
                    }
                });
            },

        })
    </script>
</div>
</body>
</html>